package controller

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"payment/app/service"
	"payment/app/validator"
)

func Index(c *gin.Context) {
	c.JSON(200, &map[string]string{"test": "1"})
}

func CreateInOrder(c *gin.Context) {
	var payEntryArg validator.PayEntryValidator
	if err := c.ShouldBind(&payEntryArg); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	if vs, msg := payEntryArg.Valid(); !vs {
		c.JSON(http.StatusBadRequest, gin.H{"error": msg})
		return
	}
	orderData := make(map[string]interface{})

	payEntry, resKey := service.GetPayEntryService().CreateInOrder(payEntryArg)
	if resKey != "" {
		orderData["code"] = "500"
		orderData["msg"] = resKey
		c.JSON(500, orderData)
		return
	}
	orderData["code"] = "200"
	orderData["data"] = payEntry
	c.JSON(200, orderData)
	return
}

func GetOrderStatus(c *gin.Context) {
	paymentOrderId := c.PostForm("payment_order_id")
	paymentId := c.PostForm("payment_id")
	sign := c.PostForm("signature")
	if paymentOrderId == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "payment_order_id is empty!"})
		return
	}
	if sign == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "payment_order_id is empty!"})
		return
	}
	if paymentOrderId == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "payment_order_id is empty!"})
		return
	}
	orderData := make(map[string]interface{})
	status, resKey := service.GetPayEntryService().GetPayOrderStatus(paymentId, paymentOrderId)
	if resKey != "" {
		orderData["code"] = "500"
		orderData["msg"] = resKey
		c.JSON(500, orderData)
		return
	}
	orderData["code"] = "200"
	orderData["msg"] = "success"
	orderData["data"] = map[string]interface{}{
		"status":           status,
		"payment_order_id": paymentOrderId,
		"payment_id":       paymentId,
	}
	c.JSON(500, orderData)
	return
}
